package com.wuad.platformwuad.module.system.service.impl;

import com.wuad.platformwuad.common.Result;
import com.wuad.platformwuad.module.system.entity.LoginUser;
import com.wuad.platformwuad.module.system.entity.SysUserEntity;
import com.wuad.platformwuad.module.system.service.LoginService;
import com.wuad.platformwuad.util.JwtUtil;
import com.wuad.platformwuad.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 登录实现类
 *
 * @author wuad
 * @date 2023年08月17日 15:34
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;


    @Override
    public Result login(SysUserEntity SysUserEntity) {

        // AuthenticationManager authentication进行用户登录认证
//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginRequest,null,loginRequest.getAuthorities());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(SysUserEntity.getUserName(), SysUserEntity.getPassword());
        //AuthenticationManager authentication进行用户登录认证，会把
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            log.info("登录失败");
            throw new RuntimeException("登录失败");
        }
        // 如果认证通过，使用userid生成一个jwt jwt存入返回结果集返回
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSysUserEntity().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 把完整的用户信息存入redis, userId作为key, jwt为value
        redisCache.setCacheObject("login:"+userId,loginUser);

        return new Result(200,"登录成功", map);
    }
}
